package wang.wangby.lazydoc.common.parameter;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Map;

import wang.wangby.lazydoc.common.DocParameterType;

public class GenericType extends DocParameterType{

	private ParameterizedType type;
	private Map<String, Type> realType;
	private Type rawType;
	
	public GenericType(ParameterizedType type, Type ownerType) {
		super(type,ownerType);
		this.type = type;
		this.rawType=type.getRawType();
		this.realType=getRealType(ownerType);
	}

	@Override
	public String getTypeName() {
		StringBuilder sb=new StringBuilder();
		sb.append(rawType.getTypeName());
		sb.append("<");
		for(Type argType:type.getActualTypeArguments()) {
			if(argType instanceof TypeVariable) {
				TypeVariable var=(TypeVariable)argType;
				sb.append(realType.get(var.getName()).getTypeName()+",");
			}else {
				sb.append(argType.getTypeName()+",");
			}
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append(">");
		return sb.toString();
	}

	@Override
	public Class getRawType() {
		return DocParameterType.getRawType(type);
	}

	@Override
	public Class getFirstGenericType() {
		for(Type argType:type.getActualTypeArguments()) {
			if(argType instanceof TypeVariable) {
				TypeVariable var=(TypeVariable)argType;
				return (Class) realType.get(var.getName());
			}else {
				return (Class)argType;
			}
		}
		throw new RuntimeException("不可能到这的,泛型的参数个数为0");
	}


}
